from rest_framework import status
from rest_framework.views import APIView
from utils.centent.cos import credential
from django.db.models import F
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, UpdateAPIView

from api import models

from api.serializer import business
from utils.common import config, add
from utils.common import filters, pagination
from utils.common.auth import JWTAuthentication


class TemporaryKeyAPIView(APIView):
    """cos临时密钥生成"""
    authentication_classes = [JWTAuthentication, ]

    def get(self, request, *args, **kwargs):
        bucket = request.user.bucket
        ret = credential(bucket=bucket)
        return Response(data=ret)


class ReleaseAPIView(CreateAPIView):
    """发布保存视图"""
    authentication_classes = [JWTAuthentication, ]
    serializer_class = business.ReleaseModelSerializer

    def post(self, request, *args, **kwargs):
        response = super(ReleaseAPIView, self).post(request, *args, **kwargs)

        # 进行自定义返回数
        data = {
            "status": 1000,
            'msg': '成功'
        }
        response.data = data

        return response


class TopicListAPIView(ListAPIView):
    """话题的视图"""
    authentication_classes = []
    # queryset = models.Topic.objects.filter(is_show=True, is_delete=False).order_by('hot', '-id')
    queryset = models.Topic.objects.filter(is_show=True, is_delete=False).order_by('-id')
    serializer_class = business.TopicModelSerializer


class IndexListAPIView(ListAPIView):
    """首页视图，支持上拉下拉更新数据"""
    authentication_classes = []

    # queryset = models.Release.objects.filter(is_show=True, is_delete=False).order_by('-hot', '-thumbs_up', '-id')
    queryset = models.Release.objects.filter(is_show=True, is_delete=False).order_by('-id')
    serializer_class = business.IndexModelSerializer
    # 用于分页(出路min_id||max_id)添加filter条件
    filter_backends = [filters.MaxFilterBackend, filters.MinFilterBackend]
    # 用于切片 添加切片条件
    pagination_class = pagination.DataLimitPagination


class IndexDetailsListAPIView(RetrieveAPIView):
    """返回首页详情视图
    http://127.0.0.1:8090/api/index/detail/31/
    """
    # 登录才能查看
    authentication_classes = [JWTAuthentication, ]
    queryset = models.Release.objects.filter(is_show=True, is_delete=False).order_by('-hot', '-thumbs_up', '-id')
    serializer_class = business.IndexDetailsModelSerializer

    def retrieve(self, request, *args, **kwargs):
        """重写retrieve视图,添加访客记录"""
        response = super(IndexDetailsListAPIView, self).retrieve(request, *args, **kwargs)
        # 在此添加访客记录
        # 判断是否登录,如果登录添加,未登录,不添加记录
        # models.Replace.object.get(pk=pk) # 返回详情视图所需的模型类数据对象
        release_obj = self.get_object()
        # print(release_obj)
        # 热度增加
        release_obj.hot *= config.HOT_COMMENT
        # print("release_obj.hot", release_obj.hot)
        release_obj.save()
        if request.user:
            query_user = models.WatchNum.objects.filter(is_show=True, is_delete=False, release=release_obj,
                                                        userinfo=request.user)
            # 判断当前动态中是否该用户的访客记录,如果有,不添加
            exist = query_user.exists()
            if not exist:
                models.WatchNum.objects.create(release=release_obj, userinfo=request.user)
                # 访问记录加一
                models.Release.objects.filter(id=release_obj.id).update(watch_num=F('watch_num') + 1)

        return response


class CommentAPIView(ListAPIView, CreateAPIView):
    """获取更多评论以及添加评论接口
    get:
    http://127.0.0.1:8090/api/comment/?root=1
    post:
    见序列化器

    &&
    保存评论视图
    序列化其里面
    """
    authentication_classes = [JWTAuthentication, ]

    def get_serializer_class(self):
        """根据需求返回序列化器

        """
        if self.request.method == 'GET':
            return business.CommentModelSerializer
        return business.PostCommentModelSerializer

    queryset = models.Comment.objects.all()
    serializer_class = get_serializer_class

    def get_queryset(self):
        """重写queryset,返回数据"""
        root = self.request.query_params.get('root')
        # 以热度进行排序,相同,以评论点赞数量
        queryset = models.Comment.objects.filter(is_delete=False, is_show=True, root=root).order_by('-hot',
                                                                                                    '-thumbs_up',
                                                                                                    '-id')
        return queryset

    def perform_create(self, serializer):
        # 执行创建传入默认的数据
        # 如果是depth==2 进行相应的修改

        serializer.save(userinfo=self.request.user)
        # 给当前的release的评论数加一,
        # 找到当前的release,利用F
        # serializer.data--->就是校验过后的数据 serializer--->相当于一个对象
        release_id = serializer.data.get('release')
        reply_id = serializer.data.get('reply')
        # print(reply_id)
        # 评论数增加(子父都加一)
        add.add_comment_num(models.Release, release_id, config.COMMENT_NUM)
        # 动态热度增加
        add.add_hot(models.Release, release_id, config.HOT_COMMENT)
        # 给父评论增加热度
        # 判断是否为子评论，如果是父评论不予处理
        if reply_id:
            add.add_hot(models.Comment, reply_id, config.HOT_COMMENT)


class ThumbsUpReleaseAPIView(APIView):
    """动态点赞视图
    http://127.0.0.1:8090/api/comment/thumbs/up/comment/31/
    """
    authentication_classes = [JWTAuthentication]

    def get(self, request, *args, **kwargs):
        data = {
            'status': 1000,
            'msg': '',
        }
        release_id = kwargs.get('pk')
        # print('pk', release_id)
        if not release_id:
            data['status'] = 1009
            data['msg'] = '无效点赞'
            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
        query_data = models.ThumbsUp.objects.filter(userinfo=self.request.user, release_id=release_id, is_delete=False,
                                                    is_show=True)
        exist = query_data.exists()
        if exist:
            # 取消点赞，动态表数量减一，点赞表，记录删除，热度不减
            # 动态表点赞数量减一
            add.del_thumbs_up(models.Release, release_id, config.THUMBS_UP)
            # 记录删除
            query_data.update(is_delete=True, is_show=False)
        else:
            # 没点新增(以前是否已经点过了，以前带你过的修改状态，不然就新增)
            query_old = models.ThumbsUp.objects.filter(userinfo=self.request.user, release_id=release_id,
                                                       is_delete=True,
                                                       is_show=False)
            exist_old = query_old.exists()
            if not exist_old:
                models.ThumbsUp.objects.create(userinfo=self.request.user, release_id=release_id)
                # 只有第一次点赞的评论的动态，热度才增加
                add.add_hot(models.Release, release_id, config.HOT_THUMBS_UP)
                # 动态表点赞数量增加
                add.add_thumbs_up(models.Release, release_id, config.THUMBS_UP)
            else:
                query_old.update(is_delete=False, is_show=True)
                # 动态表点赞数量增加
                add.add_thumbs_up(models.Release, release_id, config.THUMBS_UP)
        data['msg'] = '成功'
        return Response(data=data, status=status.HTTP_200_OK)


class ThumbsUpCommentAPIView(APIView):
    """评论点赞
    http://127.0.0.1:8090/api/comment/thumbs/up/comment/39/
    # 评论表当前记录数量(增加或减少)
    # 评论表当前记录的热度(只有第一次点赞才增加)
    # 评论点赞记录表
    """
    authentication_classes = [JWTAuthentication]

    def get(self, request, *args, **kwargs):
        data = {
            'status': 1000,
            'msg': '',
        }
        comment_id = kwargs.get('pk')
        if not comment_id:
            data['status'] = 1009
            data['msg'] = '无效点赞'
            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
        query_data = models.CommentUp.objects.filter(userinfo=self.request.user, comment_id=comment_id, is_delete=False,
                                                     is_show=True)
        exist = query_data.exists()
        if exist:
            # 评论表点赞数量减一
            add.del_thumbs_up(models.Comment, comment_id, config.THUMBS_UP)
            # 记录删除
            query_data.update(is_delete=True, is_show=False)
        else:
            # 没点新增(以前是否已经点过了，以前带你过的修改状态，不然就新增)
            query_old = models.CommentUp.objects.filter(userinfo=self.request.user, comment_id=comment_id,
                                                        is_delete=True,
                                                        is_show=False)
            exist_old = query_old.exists()
            if not exist_old:
                models.CommentUp.objects.create(userinfo=self.request.user, comment_id=comment_id)
                # 只有第一次点赞的评论，热度才增加
                add.add_hot(models.Comment, comment_id, config.HOT_THUMBS_UP)
                # 给评论点赞，其对应的动态也增加热度
                release_id = models.Comment.objects.filter(is_delete=False, is_show=True,
                                                           id=comment_id).first().release.id
                add.add_hot(models.Release, release_id, config.HOT_THUMBS_UP)
                # 评论表点赞数量增加
                add.add_thumbs_up(models.Comment, comment_id, config.THUMBS_UP)
            else:
                query_old.update(is_delete=False, is_show=True)
                # 评论表点赞数量增加
                add.add_thumbs_up(models.Comment, comment_id, config.THUMBS_UP)
        data['msg'] = '成功'
        return Response(data=data, status=status.HTTP_200_OK)


class FansFollowAPIView(APIView):
    """粉丝关注/取消视图"""
    """
    http://127.0.0.1:8090/api/fans/3/
    """

    authentication_classes = [JWTAuthentication]

    def get(self, request, *args, **kwargs):
        data = {
            'status': 1000,
            'msg': '',
        }
        # 对方的id
        fans_follow_id = int(kwargs.get('pk'))
        if not fans_follow_id:
            data['status'] = 1010
            data['msg'] = '无效操作'
            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
        if fans_follow_id == request.user.id:
            data['status'] = 1011
            data['msg'] = '不能给自己点关注'
            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
        #
        # 首先在follow表中查询到当前是否关注过该用户
        query_data = models.Follow.objects.filter(is_delete=False, is_show=True, oneself=request.user,
                                                  follow_id=fans_follow_id)
        exist = query_data.exists()
        if exist:
            # 如果关注过，进行取关操作
            # follow表中的自己关注记录删除
            query_data.update(is_delete=True, is_show=False)
            # 对方follow表中的粉丝记录删除
            models.Follow.objects.filter(is_delete=False, is_show=True, oneself_id=fans_follow_id,
                                         fan_id=request.user.id).update(is_delete=True, is_show=False)
            # 自己用户表中的关注者数量减一
            add.del_follow(models.UserInfo, request.user.id, config.FANS_UP)
            # 对方用户表中的粉丝数量数量减一
            add.del_fans(models.UserInfo, fans_follow_id, config.FANS_UP)
        else:
            # 进行关注操作
            # 判断以前是否关注过了
            query_old = models.Follow.objects.filter(oneself=request.user.id, follow_id=fans_follow_id, is_delete=True,
                                                     is_show=False)
            exist_old = query_old.exists()
            if not exist_old:
                # 如果之前没有关注过
                # 自己follow表中 关注者关系创建
                models.Follow.objects.create(oneself=request.user, follow_id=fans_follow_id)
                # 自己用户表中关注者数量加一
                add.add_follow(models.UserInfo, request.user.id, config.FANS_UP)
                # 对方follow表中粉丝新建
                models.Follow.objects.create(oneself_id=fans_follow_id, fan_id=request.user.id)
                # 对方粉丝数量加一
                add.add_fans(models.UserInfo, fans_follow_id, config.FANS_UP)
            else:
                # 如果是之前关注过的
                # follow表之前自己关注者记录恢复
                query_old.update(is_delete=False, is_show=True)
                # 自己用户表中的关注者加一
                add.add_follow(models.UserInfo, request.user.id, config.FANS_UP)
                # 对方的follow表之前粉丝记录恢复(问题)
                models.Follow.objects.filter(oneself=fans_follow_id, fan_id=request.user.id, is_delete=True,
                                             is_show=False).update(is_delete=False, is_show=True)
                # 对方用户表里面的粉丝数量数量加一
                add.add_fans(models.UserInfo, fans_follow_id, config.FANS_UP)
        data['msg'] = '成功'
        return Response(data=data, status=status.HTTP_200_OK)


class FanDetailAPIView(ListAPIView):
    """粉丝详细视图
    http://127.0.0.1:8090/api/fan/detail/
    """
    authentication_classes = [JWTAuthentication]
    queryset = models.Follow.objects.all()
    serializer_class = business.FanDetailModelSerializer

    def get_queryset(self):
        queryset = models.Follow.objects.filter(is_delete=False, is_show=True, oneself=self.request.user,
                                                fan__isnull=False).order_by('-id')
        return queryset


class FollowDetailAPIView(ListAPIView):
    """关注详细视图
    http://127.0.0.1:8090/api/follow/detail/
    """
    authentication_classes = [JWTAuthentication]
    queryset = models.Follow.objects.all()
    serializer_class = business.FollowDetailModelSerializer

    def get_queryset(self):
        queryset = models.Follow.objects.filter(is_delete=False, is_show=True, oneself=self.request.user,
                                                follow__isnull=False).order_by('-id')
        return queryset
